package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
	"sync"

	docopt "github.com/docopt/docopt-go"

	"frp/src/frp/models/client"
	"frp/src/frp/utils/log"
	"frp/src/frp/utils/version"
)

var (
	configFile string = "./frc.ini"

	usage string = `frpc is the client of frp
	
	Usage:
	    frpc [-c config_file] [-L log_file] [--log-level=<log_level>] [--server-addr=<server_addr>]
		frpc -h | --help | --version

	Options:
		-c config_file 				set config file
		-L log_file                 set output log file, include console
		--log-level=<log_level>     set log level: debug, info, warn, error (default: info)
		--server-addr=<server_addr> addr which frps is listening for, examples: 0.0.0.0:7000
		-h --help                   show help
		--version                   show version
	`
)

func main() {
	//agrs, err := docopt.Parse(usage, nil, true, version.Full(), false)
	agrs, err := docopt.ParseArgs(usage, nil, version.Full())
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	if agrs["-c"] != nil {
		configFile = agrs["-c"].(string)
	}

	err = client.LoadConf(configFile)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	if agrs["-L"] != nil {
		if agrs["-L"].(string) == "console" {
			client.LogWay = "console"
		} else {
			client.LogFile = agrs["-L"].(string)
			client.LogWay = "file"
		}
	}

	if agrs["--log_level"] != nil {
		client.LogLevel = agrs["--log_level"].(string)
	}

	if agrs["--server_addr"] != nil {
		addr := strings.Split(agrs["--server_addr"].(string), ":")
		if len(addr) != 2 {
			fmt.Println("--server-addr format error: example 0.0.0.0:7000")
			os.Exit(1)
		}

		serverPort, err := strconv.ParseInt(addr[1], 10, 64)
		if err != nil {
			fmt.Println("--server-addr format error, example 0.0.0.0:7000")
			os.Exit(1)
		}

		client.ServerAddr = addr[0]
		client.ServerPort = serverPort
	}

	log.InitLog(client.LogWay, client.LogFile, client.LogLevel)

	// wait until all control goroutine exit
	var wait sync.WaitGroup
	wait.Add(len(client.ProxyClients))

	for _, client := range client.ProxyClients {
		go ControlProcess(client, &wait)
	}

	log.Info("Start frpc success")

	wait.Wait()
	log.Warn("All proxy exit!")
}
